<template>
  <!-- 在线对话子组件 -->
  <div id="box">
    <div id="onlineChat">
      <div v-show="logoutBtn" class="topIcon" @click="logout">
        <img src="../../assets/images/home/tuichu.png" />
      </div>
      <iframe
        ref="myiframe"
        name="myiframe"
        class="iframe"
        id="myiframe"
        style="width: 0; height: 0"
        :src="`/speechService/examples/index.html`"
        frameborder="0"
        scrolling="no"
      ></iframe>
      <!-- 聊天框 -->
      <div class="chat_commento">
        <div class="chat_top">
          {{ Myname }}
          <slot name="reduceandenlarge"></slot>
        </div>
        <!-- <div class="line"></div> -->
        <!-- middle -->
        <div class="chat_middle" id="chat_middle_item">
          <!-- 左边 -->
          <!-- roletype !== 1 表示为亲属或养老院第三方（左侧） roletype == 1 表示老人角色（右侧） -->
          <div
            v-show="item.message !== ' '"
            v-for="(item, index) in chatArray"
            :key="index"
            :class="{
              chat_left: item.roletype !== 1,
              chat_right: item.roletype == 1,
              clearfix: true,
            }"
          >
            <!-- 头像和名称 -->
            <div
              :class="{
                chat_left_item_1: item.roletype !== 1,
                chat_right_item_1: item.roletype == 1,
              }"
            >
              <!-- //  0: 子女或亲属 1: 老人本身 2: 机构  -->
              <img
                id="userimg"
                :src="
                  item.roletype == 2
                    ? require('../../assets/images/users/xiaofu.jpg')
                    : item.roletype == 1
                    ? require('../../assets/images/users/oldmale.png')
                    : item.roletype == 1
                    ? require('../../assets/images/users/oldfemale.png')
                    : require('../../assets/images/users/child.png')
                "
                alt=""
              />
              <span v-if="item.roletype !== 1">{{ item.name }}</span>
              <span v-else>我</span>
            </div>
            <div
              :class="{
                chat_left_item_2: item.roletype !== 1,
                chat_right_item_2: item.roletype == 1,
              }"
            >
              <!-- 聊天时间 -->
              <div
                :class="{
                  chat_time: item.roletype !== 1,
                  chat_right_time: item.roletype == 1,
                }"
              >
                {{ item.time }}
              </div>
              <div>
                <!-- 聊天内容 -->
                <div
                  :class="{
                    chat_left_content: item.roletype !== 1,
                    chat_right_content: item.roletype == 1,
                  }"
                >
                  {{ item.message }}
                  <img
                    class="warn"
                    @click="showWarnwhy($event)"
                    v-show="item.flag == 'fail'"
                    src="../../assets/images/global/warn.png"
                  />
                </div>
                <!-- <img class="warn" @click="showWarnwhy($event)" v-show="item.flag=='fail'" src="../../assets/images/global/warn.png" /> -->
              </div>
            </div>
          </div>
        </div>
        <!-- line -->
        <div class="line"></div>
        <!-- foot -->
        <div class="chat_foot">
          <!-- context  -->
          <textarea
            v-focus="true"
            class="chat_context"
            @keydown="handleKeyCode"
            v-model="chat_context_item"
            id="chat_context_item"
            cols="30"
            rows="10"
          ></textarea>
          <div
            v-show="btnDebug"
            class="chat_log"
            id="button"
            @click="logmode()"
          >
            调试
          </div>
          <div class="chat_commit" id="button" @click="commit()">发送</div>
        </div>
      </div>
      <!-- 日志列表 -->
      <div class="logList" v-show="showlog && btnDebug" id="logList">
        <div class="chat_top" style="position: sticky; top: 0">日志列表</div>
        <!-- <div class="line"></div> -->
        <div class="logContent" id="logContent">
          <ul>
            <li v-for="(item, index) in chatLog" :key="index + '_' + index">
              <span class="logTime">{{ item.time }}</span
              ><br />
              <span class="logMessage">{{ item.content }}</span>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { mapMutations, mapState } from "vuex";
import mqtt from "mqtt";
// import moment from 'moment';
// import { trtcSpeech, chatMessage, chatRecoeds } from "../../api/index";
import { chatMessage, chatRecoeds } from "../../api/index";
import mp3 from "../../assets/music/start.mp3";
import mp30 from "../../assets/music/end.wav";
import Cookies from 'js-cookie'
import {
  MQTT_SERVICE,
  MQTT_USERNAME,
  MQTT_PASSWORD,
} from "../../utils/sysconstant";
// mqtt协议规则
const roomoptions = {
  connectTimeout: 40000,
  clientId: "appmqttjs_" + Math.random().toString(16).substr(2, 8),
  username: MQTT_USERNAME,
  password: MQTT_PASSWORD,
  clean: true,
};
export default {
  name: "onlineChat",
  data() {
    return {
      Myname: "",
      chat_context_item: "",
      roomClient: null, //ws
      Connected: false,
      chattopic: "",
      hastatustopic: "",
      // 当前账号：1   0: 子女或亲属 1: 老人本身 2: 机构
      // chatArray:[],
      showlog: true,
      btnDebug: false,
      appAnswerMusic: null,
      appAnswerEndMusic: null,
      volume:50,
      remark:'',
      mes:'',
      speechUtterance:null
      // messageVoice:null
    };
  },
  props: {
    logoutBtn: {
      type: Boolean,
      required: false,
      default: true,
    },
  },
  directives: {
    focus: {
      inserted: function (el, { value }) {
        if (value) {
          el.focus();
        }
      },
    },
  },
  computed: {
    ...mapState({
      currentUserId: (state) => state.currentUserId, //当前的用户id
      loginUserInfo: (state) => state.loginUserInfo,
      userInfoDetails: (state) => state.userInfoDetails, //用户详细信息
      chatClient: (state) => state.chatClient, //聊天的mq
      chatLog: (state) => state.chatLog, //聊天日志
      chatArray: (state) => state.chatArray, //聊天内容
    }),
  },
  watch: {
    chat_context_item(val) {
      this.chat_context_item = val;
    },
    // 监听聊天内容改变时，页面滚动至聊天记录最底部
    chatArray() {
      let ele = document.getElementById("chat_middle_item");
      if (ele.scrollHeight > ele.clientHeight) {
        ele.scrollTop = ele.scrollHeight;
        ele.scrollTo({ top: ele.scrollHeight, behavior: "smooth" });
      }
    },
    // 监听日志列表
    chatLog() {
      this.$nextTick(function () {
        let elelogContent = document.getElementById("logList");
        if (elelogContent.scrollHeight > elelogContent.clientHeight) {
          elelogContent.scrollTop = elelogContent.scrollHeight;
          elelogContent.scrollTo({
            top: elelogContent.scrollHeight,
            behavior: "smooth",
          });
        }
      });
    },
  },
  created() {
    this.Myname = this.userInfoDetails.account.name;
    this.chattopic = this.currentUserId + "/chat";
    this.hastatustopic = this.currentUserId + "/chat/mpd/state";
    this.getChatRecords();
      this.appAnswerMusic = null;
      this.appAnswerMusic = new Audio();
      this.appAnswerMusic.src = mp3;
      this.appAnswerEndMusic=null
      this.appAnswerEndMusic = new Audio();
      this.appAnswerEndMusic.src = mp30;
  },
  mounted() {
    // let durationTime = localStorage.getItem("durationSelected");
    // console.log(durationTime * 1000,'durationTime');
    // 是否显示调试模式
    // if (localStorage.getItem("modeSelected") == "1") this.btnDebug = true;
    if (Cookies.get("modeSelected") == "1") this.btnDebug = true;
    this.connectMq();
    console.log("语音聊天mounted");
    // 没有配置过麦克风
    // if (!localStorage.getItem("audioSelectedValue")) {
    if (!Cookies.get("audioSelectedValue")) {
      console.log("没有配置过麦克风");
      // navigator.mediaDevices?.enumerateDevices 获取当前设备上可用的媒体设备（如摄像头、麦克风等）的列表
      if (!navigator.mediaDevices?.enumerateDevices) {
        console.log("enumerateDevices() not supported.");
      } else {
        // navigator.mediaDevices.enumerateDevices 设备列表是一个 Promise 对象，它将返回一个包含设备信息的数组。
        navigator.mediaDevices
          .enumerateDevices()
          .then((devices) => {
            for (var i = 0; i < devices.length; i++) {
              // kind为audioinput 设置列表中的音频输入设备
              // label 表示设备的可读标签，通常包含设备的名称或描述。
              if (devices[i].kind == "audioinput") {
                // localStorage.setItem("audioSelectedValue", devices[i].label);
                Cookies.set("audioSelectedValue", devices[i].label);
                break;
              }
            }
          })
          .catch((err) => {
            console.error(`${err.name}: ${err.message}`);
          });
      }
    }
    this.updated();
    this.$nextTick(function () {
      let elelogContent = document.getElementById("logList");
      if (elelogContent.scrollHeight > elelogContent.clientHeight) {
        elelogContent.scrollTop = elelogContent.scrollHeight;
        elelogContent.scrollTo({
          top: elelogContent.scrollHeight,
          behavior: "smooth",
        });
      }
    });
    window.addEventListener("onbeforeunload", () => {
      console.log("页面关闭onbeforeunload");
    });
    window.addEventListener("onload", () => {
      console.log("页面关闭onload");
    });
    this.initSpeack();
  },
  methods: {
    ...mapMutations(["setChatClient", "setChatLog", "setChatArray"]),
    showWarnwhy(e) {
      e.target.style = "display:none";
    },
    // 创建mq连接
    connectMq() {
      let that = this;
      var _this = this;

      //未创建mq
      if (!this.chatClient) {
        console.log("**************在线聊天开始连接**************");
        that.$store.commit("setChatLog", {
          time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
          content: "在线聊天开始连接mq",
        });
        that.roomClient = mqtt.connect(MQTT_SERVICE, roomoptions);
        that.$store.commit("setChatClient", that.roomClient);
        console.log("mqtt是否链接成功", that.roomClient.connected);
        if (!that.roomClient.connected) {
          // mqtt连接
          that.roomClient.on("connect", () => {
            console.log("**************在线聊天mq连接成功**************");
            that.$store.commit("setChatLog", {
              time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
              content: "在线聊天mq连接成功",
            });
            that.Connected = true; //ws连接成功
            //连接成功后订阅消息
            //qos为0 最多一次的传输
            that.roomClient.subscribe(that.chattopic, { qos: 0 }, (error) => {
              if (!error) {
                that.$store.commit("setChatLog", {
                  time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                  content: "在线聊天mq订阅成功",
                });
                console.log("**************在线聊天mq订阅成功**************",that.chattopic);
              } else {
                that.$store.commit("setChatLog", {
                  time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                  content: "在线聊天mq订阅失败",
                });
                console.log("**************在线聊天mq订阅失败**************",that.chattopic);
              }
            });
            that.roomClient.subscribe(
              that.hastatustopic,
              { qos: 0 },
              (error) => {
                if (!error) {
                  that.$store.commit("setChatLog", {
                    time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                    content: "在线聊天HAmq订阅成功",
                  });
                  console.log(
                    "**************HAmq订阅成功**************",
                    that.hastatustopic
                  );
                } else {
                  that.$store.commit("setChatLog", {
                    time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                    content: "在线聊天HAmq订阅失败",
                  });
                  console.log(
                    "**************HAmq订阅失败**************",
                    that.hastatustopic
                  );
                }
              }
            );
          });
        }
        // 断开发起重连
        that.roomClient.on("reconnect", (error) => {
          that.$store.commit("setChatLog", {
            time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
            content: "在线聊天mq正在重连",
          });
          console.log("在线聊天mq正在重连:", error);
        });
        that.roomClient.on("message", (topic, message) => {
          console.log('message',message);
          let data = JSON.parse(message);
          _this.$store.commit("setChatLog", {
              time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
              content: "收到来自"+ topic +"的消息:"+data.message,
          });
          console.log("收到来自", topic, "的消息", data);
          if(data!== 1){
            this.volume=data.soundVolume!== undefined ? parseInt(data.soundVolume) : 50;
          }
          console.log('data.soundVolume',data.soundVolume,'this.volume',this.volume);

          if (topic == that.chattopic) {
            if (parseInt(data.roletype) !== 1 && data.message) {
              this.mes =data.message
              _this.$store.commit("setChatLog", {
                time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                content: "接收到消息，即将进行播放："+ this.mes,
              });
              console.log('接收到消息，即将进行播放',this.mes,'data.message')
              this.pushData(data);
              window.speechSynthesis.cancel()
              // 销毁上一个未播放完成的语音
              // if(_this.messageVoice !== null){
              //   _this.messageVoice.pause()
              //   _this.messageVoice.removeAttribute('src')
              //   _this.messageVoice.load()
              //   _this.messageVoice= null
              // }
              // speechSynthesis.speak(that.speechUtterance);
              this.speak({text:this.mes,volume:this.volume/100});
              // 播放接收到的消息message
              // {
              //   "id":0,
              //   "modeltype":1,
              //   "userID":"16427281230",
              //   "roletype":2,
              //   "senderType":3,
              //   "senderID":"guest_xckw_service1",
              //   "senderName":"科委客服中心",
              //   "message":"你好",
              //   "requestTime":"2023-10-20T11:20:00.52125408:00"
              // }
            }
          }
          // if (topic == that.hastatustopic) {
          //   // if (parseInt(data) == 1) {
          //     console.log("收到ha消息",that.hastatustopic,'that.hastatustopic',data);
          //     if (document.getElementById("myiframe")) {
          //       that.opentimeIdenty('HA');
          //     }
          //   // }
          // }
        });
        //如果连接错误，打印错误
        that.roomClient.on("error", function (err) {
          that.$store.commit("setChatLog", {
            time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
            content: "在线聊天mq连接错误",
          });
          console.log("在线聊天mq连接错误了 err=>", err);
          // that.Connected = false;
          if (that.Connected) {
            that.roomClient.end();
          }
          that.Connected = false;
        });
      }
    },

    // 初始化文字转语音
    initSpeack(){
      var _this = this;

      if (!window.SpeechSynthesisUtterance) {
          console.log('当前浏览器不支持文字转语音服务',window.SpeechSynthesisUtterance,speechSynthesis)
          _this.$store.commit("setChatLog", {
            time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
            content: "当前浏览器不支持文字转语音服务-----"+window,
          });
          return;
      }

      this.speechUtterance = new SpeechSynthesisUtterance();
      console.log('初始化speechUtterance',this.speechUtterance,speechSynthesis)
      _this.$store.commit("setChatLog", {
        time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
        content: "初始化speechUtterance成功",
      });
    },
    // 语音合成
    async speak( {text, speechRate, lang, volume, pitch} ) {
    // async speak( {text} ) {

      let that = this;
      var _this = this;

      var messageVoice=new Audio()
      var url="https://tsn.baidu.com/text2audio?tex="+encodeURI(text)+"&lan=zh&cuid=lHte3TbikdvWNXN7y3Mt8bAFpbM8AOLf&ctp=1&tok=24.7439ccc5cc04a0491ab5db786e171894.2592000.1719462957.282335-75710443"
      messageVoice.src = url
      messageVoice.play()
      messageVoice.addEventListener('ended', function () {
          console.log('播音结束');
          _this.$store.commit("setChatLog", {
            time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
            content: "播放结束",
          });
          _this.$store.commit("setChatLog", {
            time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
            content: "trtc---开始语音识别",
          });
          if (document.getElementById("myiframe")) {
              that.opentimeIdenty('mq');
          }
      }, false);
      // _this.messageVoice = new Audio();
      // This.SpeechSynthesisUrl = ""
      // This.messageVoice.src = ""
      // await trtcSpeech("message=" + text)
      //   .then((res) => {
      //     console.log("调用接口的结果", res);
      //     if (res.data.code == 0) {
      //       _this.messageVoice.src = res.data.result;
      //       var re=JSON.stringify(res);
      //       _this.$store.commit("setChatLog", {
      //         time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
      //         content: "trtc---语音合成成功:"+re,
      //       });
      //       this.$message.success("语音合成成功");
      //       _this.messageVoice.play()
      //       _this.$store.commit("setChatLog", {
      //         time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
      //         content: "trtc---语音播放",
      //       });
      //       _this.messageVoice.addEventListener('ended', function () {
      //           console.log('播音结束');
      //           _this.$store.commit("setChatLog", {
      //             time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
      //             content: "播放结束",
      //           });
      //           _this.$store.commit("setChatLog", {
      //             time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
      //             content: "trtc---开始语音识别",
      //           });
      //           if (document.getElementById("myiframe")) {
      //              that.opentimeIdenty('mq');
      //           }
      //       }, false);
      //     } else {
      //       _this.$store.commit("setChatLog", {
      //         time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
      //         content: "trtc---语音合成失败",
      //       });
      //       this.$message.error("语音合成失败");
      //     }
      //   })
      //   .catch((error) => {
      //     console.log("获取失败", error);
      //     var er=JSON.stringify(error)
      //     _this.$store.commit("setChatLog", {
      //         time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
      //         content: "trtc---语音合成失败:"+er,
      //       });
      //     this.$message.error("语音合成失败");
      //   });



      _this.$store.commit("setChatLog", {
        time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
        content: "进行语音合成--------",
      });
      console.log('进行语音合成--------',text)
      if (!text) {
          return;
      }           
      // const speechUtterance = new SpeechSynthesisUtterance();
      that.speechUtterance.text = text;
      that.speechUtterance.rate = speechRate || 1;  //语速
      that.speechUtterance.lang = lang || 'zh-CN';  //语言
      that.speechUtterance.volume = volume ||0.5;   //声音volume 为0.0——1.0
      that.speechUtterance.pitch = pitch || 1;      //音调

      console.log('speechUtterance',that.speechUtterance)
      var voices = window.speechSynthesis.getVoices()
      console.log('speechUtterance.voices',window.speechSynthesis.getVoices())
      // 设置实例的voice，说话的声音
      that.speechUtterance.voice = voices.filter(function(voice) { return voice.localService == true && voice.lang == "zh-CN"; })[0];
      console.log('speechUtterance',that.speechUtterance)
      // 语音合成出错
      that.speechUtterance.addEventListener('error', (event) => {
        var err=JSON.stringify(event.error)
          // 朗读错误时触发
          _this.$store.commit("setChatLog", {
            time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
            content: "朗读错误："+err,
          });
          console.error('朗读错误:', event, event.error);
          if (document.getElementById("myiframe")) {
             that.opentimeIdenty('mq');
          }
      });
      // 实例属性，语音合成结束
      that.speechUtterance.onend = function() {
          // endEvent && endEvent();
          _this.$store.commit("setChatLog", {
            time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
            content: "朗读结束,准备进行语音识别",
          });
          console.log('朗读结束,准备进行语音识别');
          if (document.getElementById("myiframe")) {
             that.opentimeIdenty('mq');
          }
          console.log('speechUtterance',that.speechUtterance)
      };
      
      // 实例属性，语音合成开始
      that.speechUtterance.onstart = function() {
          // startEvent && startEvent();
          _this.$store.commit("setChatLog", {
            time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
            content: "朗读开始",
          });
          console.log('朗读开始');
      };
      that.speechUtterance.onerror= function() {
          // startEvent && startEvent();
          console.log('朗读错误');
      };
      //在语音合成过程中达到特定边界时触发的事件处理程序。
      that.speechUtterance.onboundary= () => {
          // console.log('边界');
      }
      // speechSynthesis.speak(that.speechUtterance);
      return that.speechUtterance;
    },

    pushData(data) {
      this.$store.commit("setChatArray", {
        roletype: data.roletype,
        time: new Date().Format("yyyy-MM-dd hh:mm:ss"), //moment(data.requestTime).format('YYYY-MM-DD HH:mm:ss'),
        name: data.senderName,
        message: data.message,
      });
      this.updated();
    },
    logout() {
      //退出到首页
      this.$router.push("/");
      // this.roomClient.end();
    },
    beforeDestroy() {
      console.log("页面关闭销毁");
    },
    destroyed() {
      console.log("页面关闭销毁");
    },
    // 聊天信息定位到最下方
    updated: function () {
      this.$nextTick(function () {
        var div = document.getElementById("chat_middle_item");
        if (div) div.scrollTop = div.scrollHeight;
      });
    },
    // 对方的话念完开始语音识别
    opentimeIdenty(type) {
      // let durationTime = localStorage.getItem("durationSelected");
      let durationTime = Cookies.get("durationSelected");
      // console.log('durationTime',durationTime);
      var _this = this;
      // 从父窗口向iframe窗口发送数据
      document
        .getElementById("myiframe")
        .contentWindow.postMessage({ cmd: "chatstart" }, "*");
      _this.$store.commit("setChatLog", {
        time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
        // content: "收到HA的消息",
        content: "收到"+type+"消息",
      });
      // 可以进行识别时发出提示音
      _this.appAnswerMusic.play();
      _this.$store.commit("setChatLog", {
        time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
        content:
          "[" +
          // localStorage.getItem("audioSelectedValue") +
          Cookies.get("audioSelectedValue") +
          "]实时语音转文字:开始",
      });
      if (endTime) clearTimeout(endTime);
      let endTime = setTimeout(() => {
        // 不说话10秒结束
        console.log(durationTime+"秒未结束");
        // 语音识别结束播放提示音
        _this.appAnswerEndMusic.play();
        _this.$store.commit("setChatLog", {
          time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
          content: durationTime+"秒无人声，实时识别结束",
        });
        if (document.getElementById("myiframe"))
          document
            .getElementById("myiframe")
            .contentWindow.postMessage({ cmd: "chatend" }, "*");
      }, durationTime * 1000);
      window.onmessage = function (e) {
        switch (e.data.cmd) {
          case "chatchange":
            clearTimeout(endTime);
            _this.chat_context_item = e.data.params.currentText;
            document.getElementById("chat_context_item").value =
              e.data.params.currentText;
            break;
          case "aWorldend": // 识别变化时，走不到一句话结束
            clearTimeout(endTime);
            _this.chat_context_item = e.data.params.currentText;
            document.getElementById("chat_context_item").value =
              e.data.params.currentText;
            document
              .getElementById("myiframe")
              .contentWindow.postMessage({ cmd: "chatend" }, "*");
            _this.commit();
            // 语音识别结束播放提示音
            _this.appAnswerEndMusic.play();
            _this.$store.commit("setChatLog", {
              time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
              content:
                "[" +
                // localStorage.getItem("audioSelectedValue") 
                Cookies.get("audioSelectedValue")
                +
                "]实时语音转文字:结束" +
                e.data.params.currentText,
            });
            break;
        }
      };
    },
    handleKeyCode(e) {
      // enter键
      if (e.keyCode == 13) {
        if (!(e.ctrlKey || e.metaKey)) {
          e.cancelBubble = true; //ie阻止冒泡行为
          e.stopPropagation(); //Firefox阻止冒泡行为
          e.preventDefault(); //取消事件的默认动作*换行
          this.commit();
        } else {
          this.chat_context_item = this.chat_context_item + "\n";
        }
      }
    },
    // 发送消息
    async commit() {
      if (!this.chat_context_item.trim()) {
        this.$message.info("请输入消息");
        return;
      }
      var param = {
        model_type: 1,
        role_type: 1,
        user_id: this.currentUserId,
        sender_type: 2,
        sender_id: this.loginUserInfo.userId,
        sender_name: this.userInfoDetails.account.name,
        chat_message: this.chat_context_item,
        volume:this.volume,
        remark:this.remark
      };
      console.log('发送消息',param)
      await chatMessage(param)
        .then((res) => {
          console.log("调用接口的结果", res);
          if (res.code == 0 && this.chat_context_item.trim !== "") {
            console.log("发送成功", res);
            this.$store.commit("setChatArray", {
              roletype: 1,
              time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
              name: "我",
              message: this.chat_context_item,
              flag: "success",
            });
          } else {
            this.$store.commit("setChatArray", {
              roletype: 1,
              time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
              name: "我",
              message: this.chat_context_item,
              flag: "fail",
            });
          }
          this.chat_context_item = "";
          document.getElementById("chat_context_item").value = "";
          this.updated();
        })
        .catch((error) => {
          console.log("获取失败", error);
          this.$store.commit("setChatArray", {
            roletype: 1,
            time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
            name: "我",
            message: this.chat_context_item,
            flag: "fail",
          });
          this.chat_context_item = "";
          this.updated();
        });
    },
    logmode() {
      this.showlog = !this.showlog;
      // this.speak({text:'你好'});
    },
    // 获取聊天记录
    async getChatRecords() {
      var param = {
        isUserID: 1,
        userID: this.currentUserId,
        isDate: 1,
        date: new Date(new Date().getTime() - 1 * 60 * 60 * 1000).Format(
          "yyyy-MM-dd hh:mm:ss"
        ), //1小时前
        date2: new Date().Format("yyyy-MM-dd hh:mm:ss"),
      };
      // 聊天记录查询
      await chatRecoeds(param)
        .then((res) => {
          if (res.code == 0) {
            let data = res.data.records;
            // 清空聊天记录
            this.$store.commit("setChatArrayNull");
            data.forEach((item) => {
              // 设置聊天记录
              this.$store.commit("setChatArray", {
                roletype: item.role_type,
                time: item.update_time.replace("T", " "),
                name: item.sender_name,
                message: item.chat_message,
                flag: "success",
              });
            });
            this.updated();
          } else {
            console.log("调用接口失败");
          }
        })
        .catch((error) => {
          console.log("获取失败", error);
        });
    },
  },
};
</script>
<style scoped>
* {
  margin: 0;
  padding: 0;
}
ul li {
  list-style: none;
}
#box {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
::-webkit-input-placeholder {
  color: #fff;
}
:-moz-placeholder {
  color: #fff;
}
::-moz-placeholder {
  color: #fff;
}
::-ms-input-placeholder {
  color: #fff;
}
#onlineChat {
  text-align: left;
  display: flex;
  justify-content: center;
  margin-right: 5px;
}
.topIcon,
.topIcon img {
  width: 3.5rem;
  height: 3.5rem;
  margin-right: 2rem;
  position: absolute;
  right: 0;
  top: 1rem;
  cursor: pointer;
  z-index: 1;
}
/* 滚动轴样式 */
/*  // 滚动轴整体，主要设置宽度*/
::-webkit-scrollbar {
  width: 6px;
  height: 2px;
}
/*// 滚动轴的背景区域*/
::-webkit-scrollbar-track {
  background: transparent;
}
/*// 滚动轴*/
::-webkit-scrollbar-thumb {
  border-radius: 5px;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
  background: rgba(0, 0, 0, 0.1);
}

/*// 滚动轴浮动样式*/
::-webkit-scrollbar-thumb:hover {
  border-radius: 5px;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
  background: rgba(189, 118, 118, 0.3);
}
.chat_commento {
  width: 39rem;
  border-radius: 10px;
  border: 2px solid #f4f5f7;
  background: #fff;
  margin-top: 0;
  height: 36.5rem;
  box-sizing: border-box;
}
.clearfix::after {
  content: "";
  display: block;
  clear: both;
  width: 0;
  height: 0;
  line-height: 0;
  visibility: hidden;
}
/* top */
.chat_top {
  width: 100%;
  height: 50px;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  padding-left: 20px;
  padding-right: 20px;
  font-size: 20px;
  line-height: 50px;
  box-sizing: border-box;
  font-weight: 550;
  border-width: 0px;
  /* position: sticky;
    top: 0; */
  background: #fff;
  border-bottom: 5px;
  border-color: #f4f5f7;
  border-style: solid;
}
/* middle */
/* 左边 */
.chat_middle {
  width: 100%;
  height: calc(100% - 188px);
  position: relative;
  box-sizing: border-box;
  overflow-y: scroll;
  border-width: 0px;
}
.chat_left {
  width: 100%;
  margin-top: 20px;
  margin-bottom: 20px;
}
.chat_left_item_1 {
  color: #333;
  font-size: 14px;
  width: 50px;
  /* height: 90px; */
  float: left;
  margin-top: 10px;
  margin-left: 10px;
  margin-right: 10px;
  text-align: center;
  word-wrap: break-word;
  word-break: break-all;
}
.chat_left_item_2 {
  width: 55%;
  min-height: 90px;
  float: left;
  margin-top: 10px;
}
.chat_left_item_2 .chat_left_chat {
  float: left;
}
.chat_left_item_2 .chat_left_content {
  padding: 15px;
  margin-top: 10px;
  background-color: #f4f5f7;
  display: inline-block;
  border-radius: 10px;
  border-top-left-radius: 0px;
  max-width: 90%;
  word-wrap: break-word;
  word-break: break-all;
  white-space: pre-line;
}
/* 右边 */
.chat_right {
  width: 100%;
  margin-top: 20px;
  margin-bottom: 20px;
}
.chat_right_item_1 {
  width: 50px;
  float: right;
  margin-top: 10px;
  margin-left: 10px;
  margin-right: 10px;
  text-align: center;
  color: #333;
  font-size: 14px;
}
.chat_right_item_2 {
  width: 55%;
  min-height: 90px;
  float: right;
  margin-top: 10px;
}
#userimg {
  height: 50px;
  max-width: 50px;
}
.chat_right_time {
  width: 100%;
  text-align: right;
}
.clearfix::after {
  display: block;
  content: "";
  height: 0;
  clear: both;
}
.chat_right_content {
  max-width: 90%;
  word-wrap: break-word;
  word-break: break-all;
  float: right;
  padding: 15px;
  border-radius: 10px;
  margin-top: 10px;
  border-top-right-radius: 0px;
  background-color: rgb(149, 236, 105);
  color: #333;
  white-space: pre-line;
  position: relative;
}
/* foot */
.chat_foot {
  width: 100%;
  height: 130px;
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
  position: relative;
}
.chat_context {
  width: 100%;
  height: 61%;
  font-size: 17px;
  box-sizing: border-box;
  outline: none;
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
  border-width: 0px;
  padding: 16px;
  font-size: 16px;
  font-weight: 400;
  line-height: 24px;
}
.chat_commit {
  width: 80px;
  height: 30px;
  /* width: 6.33rem;
  height: 2.38rem; */
  color: white;
  background-color: rgb(50, 128, 190);
  line-height: 30px;
  text-align: center;
  border-radius: 5px;
  position: absolute;
  right: 10px;
  bottom: 20px;
  margin-right: 10px;
  cursor: pointer;
}
.chat_context {
  /* 文本框不能缩放 */
  resize: none;
  overflow-y: scroll;
}
.chat_context::placeholder {
  color: black;
  font-weight: 500k;
}
.line {
  width: 100%;
  border-top: 1px;
  border-color: #f4f5f7;
  border-style: solid;
}
.warn {
  vertical-align: middle;
  float: right;
  /* margin: 23.5px 10px 23.5px 0; */
  width: 25px;
  cursor: pointer;
  position: absolute;
  left: -30px;
  top: 50%;
  transform: translateY(-50%);
}
.logList {
  height: 36.5rem;
  width: 15rem;
  background: #fff;
  border: 2px solid #f4f5f7;
  overflow-x: hidden;
  box-sizing: border-box;
  overflow-y: scroll;
  border-radius: 10px;
}
.logContent {
  padding: 0 1rem 0 1rem;
  font-size: 0.7rem;
}
.chat_log {
  width: 80px;
  height: 30px;
  /* width: 6.33rem;
  height: 2.38rem; */
  color: white;
  background-color: rgb(50, 128, 190);
  line-height: 30px;
  text-align: center;
  border-radius: 5px;
  position: absolute;
  right: 100px;
  bottom: 20px;
  margin-right: 10px;
  cursor: pointer;
}
.logTime {
  line-height: 1.2rem;
}
.logMessage {
  line-height: 1.5rem;
}
</style>
